// API 日志模块：本地持久化、查询与清理

const STORAGE_KEY = 'api_logs_v1';
const MAX_LOGS = 1000; // 环形队列上限

function nowIso() {
	return new Date().toISOString();
}

function loadAll() {
	try {
		const raw = uni.getStorageSync(STORAGE_KEY) || '[]';
		return JSON.parse(raw);
	} catch (e) {
		return [];
	}
}

function saveAll(list) {
	try {
		uni.setStorageSync(STORAGE_KEY, JSON.stringify(list));
	} catch (e) {
		// 存储失败忽略
	}
}

export function recordLog(entry) {
	const list = loadAll();
	list.push({
		id: Date.now() + '-' + Math.random().toString(36).slice(2, 8),
		timestamp: nowIso(),
		...entry
	});
	// 控制容量
	if (list.length > MAX_LOGS) {
		list.splice(0, list.length - MAX_LOGS);
	}
	saveAll(list);
}

export function queryLogs({ keyword = '', method = '', status = '', success = undefined, from = '', to = '', page = 1, pageSize = 20 } = {}) {
	const all = loadAll();
	let filtered = all;
	if (keyword) {
		const kw = keyword.toLowerCase();
		filtered = filtered.filter(i => (i.url || '').toLowerCase().includes(kw) || (i.errorMessage || '').toLowerCase().includes(kw));
	}
	if (method) {
		filtered = filtered.filter(i => (i.method || '').toUpperCase() === method.toUpperCase());
	}
	if (status) {
		filtered = filtered.filter(i => String(i.status) === String(status));
	}
	if (typeof success === 'boolean') {
		filtered = filtered.filter(i => !!i.success === success);
	}
	if (from) {
		filtered = filtered.filter(i => i.timestamp >= from);
	}
	if (to) {
		filtered = filtered.filter(i => i.timestamp <= to);
	}

	const total = filtered.length;
	const start = (page - 1) * pageSize;
	const end = start + pageSize;
	return {
		total,
		list: filtered.slice(start, end)
	};
}

export function clearLogs() {
	saveAll([]);
}

export function getStats() {
	const all = loadAll();
	const total = all.length;
	const success = all.filter(i => i.success).length;
	const fail = total - success;
	return { total, success, fail };
} 